package com.ve.s2g.chain

import com.natpryce.konfig.Key
import com.natpryce.konfig.stringType
import com.ve.s2g.getLogger
import com.ve.s2g.getS2gConfig
import com.ve.s2g.getString4Cfg
import com.ve.s2g.pojo.Project
import com.ve.s2g.service.GitlabService
import com.ve.s2g.util.Constants
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.util.*

abstract class AbstractHandler {
    companion object {
        val prefix="s2gconfig"
    }
    var nextHandler: AbstractHandler? = null
    var step: Int = 0

    var gitlabService : GitlabService?=null

    internal fun setNextHandler(abstractHandler: AbstractHandler) {
        this.nextHandler = abstractHandler
    }

    internal fun getString4Cfg(key:String):String{
        return getString4Cfg(step,key)
    }
    abstract fun deal(dealObject: Any?)
}


@Component
class HandlerService{

    @Autowired
    private var gitlabService: GitlabService?=null

    fun finishingHandler(): AbstractHandler? {
        var handlerStack = Stack<AbstractHandler>()
        var i = 0
        Constants.HANDLERS.split("\\s*-\\s*".toRegex()).forEach {
            val c = Class.forName(it)
            val temp = c.newInstance() as AbstractHandler
            temp.step = ++i
            temp.gitlabService = this.gitlabService
            handlerStack.push(temp)
        }
        var number1:AbstractHandler? = null
        while (handlerStack.isNotEmpty()) {
            number1 = handlerStack.pop()
            if (handlerStack.isNotEmpty())
                handlerStack.peek().setNextHandler(number1)
        }
        return number1
    }
}
